<?php

namespace app\common\model;

use think\Env;
use think\Exception;
use think\Model;

/**
 * 模型
 */
class Car extends Model
{
    // 表名
    protected $name = 'car';
    protected $deleteTime = false;
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function getVinAttr($value) {
        return $value ? $value : '';
    }

    public function getProvinceAttr($value) {
        return $value ? $value : '';
    }

    public function getCarNumbersAttr($value) {
        return $value ? $value : '';
    }

    public function getMileageAttr($value)
    {
        return $value == 0 ? '' : $value;
    }



    public function brand()
    {
        return $this->belongsTo('car_brands', 'brand_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function series()
    {
        return $this->belongsTo('car_series', 'series_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function member()
    {
        return $this->belongsTo('member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 我的车库
     * @param $member_id
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getCarListByMemberId($member_id)
    {
        return self::alias('a')
            ->field('a.id,a.is_default,b.name,b.logo,c.name series_name')
            ->join('fa_car_brands b', 'a.brand_id = b.id', 'left')
            ->join('fa_car_series c', 'a.series_id = c.id', 'left')
            ->order(['a.is_default'=>'desc','a.createtime'=>'desc'])
            ->where(['a.member_id'=>$member_id,'is_del'=>0])->order('a.createtime desc')->paginate(10)->each(function ($item) {
                $item['logo'] = Env::get('app.app_host') . $item['logo'];
                return $item;
            });
    }


    public static function del($car_id,$member_id)
    {
        $data = self::find(['id'=>$car_id,'member_id'=>$member_id]);
        if ($data)
            throw new Exception('11111');

    }


}
